package net.orange.framework.dao;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import net.orange.architecture.db.PositiveCacheDao;
import net.orange.architecture.db.Condition;
import net.orange.architecture.db.Conditions;
import net.orange.architecture.db.IObjectManager;
import net.orange.architecture.model.BaseValueObject;
import net.orange.framework.model.Commoninfo;
import net.orange.framework.model.CommoninfoType;

/**
 * The ICommoninfoDao implement in Hibernate and cache in the memory.
 */
public class CacheCommoninfoDao extends PositiveCacheDao implements ICommoninfoDao {
	
	/**
	 * Cache hash Map for common info. 
	 */
	private static Map<Object, Object> cache = new HashMap<Object, Object>();
	/**
	 * Constructor with the target dao.
	 * @param target The target dao.
	 */
	public CacheCommoninfoDao(IObjectManager target) {
		setTarget(target);
	}	
	/* (non-Javadoc)
	 * @see net.orange.architecture.db.CacheDao#getKey(net.orange.architecture.vo.BaseValueObject)
	 */
	@Override
	protected Object getKey(BaseValueObject b0) throws Exception {
		Commoninfo commoninfo = (Commoninfo) b0;
		return commoninfo.getType() + "-" + commoninfo.getCode();
	}

	/* (non-Javadoc)
	 * @see net.orange.architecture.db.CacheDao#getCache()
	 */
	@Override
	public Map<Object, Object> getCache() {
		return cache;
	}

	/* (non-Javadoc)
	 * @see net.orange.architecture.db.CacheDao#setCache(java.util.Map)
	 */
	@Override
	public void setCache(Map<Object, Object> cache) {
		CacheCommoninfoDao.cache = cache;
	}
	/* (non-Javadoc)
	 * @see net.orange.architecture.db.CacheDao#refreshCache()
	 */
	@Override
	protected void refreshCache() throws Exception{
		super.refreshCache();
		
		for (CommoninfoType ct : CommoninfoType.values()) {
			Conditions cds = new Conditions();
			cds.add(new Condition("type", ct.name()));
			Collection tlist = list(cds);
			cache.put("_" + ct.name(), tlist);
		}
	}
	/* (non-Javadoc)
	 * @see net.orange.framework.commoninfo.dao.ICommoninfoDao#findByKey(java.lang.String, java.lang.String)
	 */
	public Commoninfo findByKey(String type, String code) throws Exception{
		return (Commoninfo) super.findByKey(type + "-" + code);
	}
	/* (non-Javadoc)
	 * @see net.orange.framework.commoninfo.dao.ICommoninfoDao#listByKey(java.lang.String)
	 */
	public Collection listByKey(String type) throws Exception{
		return (Collection) super.findByKey("_" + type);
	}
}
